package com.stox.ui.swing.event;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;

import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import com.stox.design.Callback;
import com.stox.event.AbstractModelSelectionEvent;
import com.stox.model.AbstractModel;
import com.stox.ui.swing.util.SwingUtil;
import com.stox.ui.swing.widget.NavigatorPopupMenu;
import com.stox.ui.swing.widget.wrapper.JTree;

@Component
public class NavigatorTreeMouseAdapter extends MouseAdapter {

	@Autowired
	private NavigatorPopupMenu navigatorPopupMenu;
	
	@Autowired
	private ApplicationEventPublisher applicationEventPublisher;
	
	@Override
	public void mouseReleased(final MouseEvent e) {
		SwingUtil.executeInFreeze((java.awt.Component)e.getSource(), new Callback<Object, Object>(){
			@Override
			public Object execute(Object payload) {
				if(SwingUtilities.isRightMouseButton(e)){
					navigatorPopupMenu.show((java.awt.Component)e.getSource(), e.getX(), e.getY());
				}else if(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
					JTree tree = (JTree)e.getSource();
					DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getSelectionPath().getLastPathComponent();
					if(node.getUserObject() instanceof AbstractModel) {
						applicationEventPublisher.publishEvent(new AbstractModelSelectionEvent<AbstractModel>(Arrays.asList((AbstractModel)node.getUserObject())));
					}
				}
				return null;
			}
		}, null);
	}
}
